<?php
/**
 * Created by PhpStorm.
 * User: MACD
 * Date: 14-7-20
 * Time: 下午8:50
 */

class User extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->helper('captcha');
        $this->load->model('user_model');
    }

    public function signup()
    {
        if($this->input->post('username'))
        {
            $config = array(
                array(
                    'field'=>'username',
                    'label'=>'用户名',
                    'rules'=>'trim|min_length[3]|max_length[12]|callback_username_check|xss_clean'
                ),
                array(
                    'field'=>'password',
                    'label'=>'密码',
                    'rules'=>'required'
                ),
                array(
                    'field'=>'password1',
                    'label'=>'确认密码',
                    'rules'=>'required|matches[password]'
                ),
                array(
                    'field'=>'phone',
                    'label'=>'联系电话',
                    'rules'=>'trim|required|is_natural|min_length[11]|max_length[11]'
                ),
                array(
                    'field'=>'captcha',
                    'label'=>'验证码',
                    'rules'=>'callback_cap_check'
                )
            );
            $this->form_validation->set_rules($config);
            if($this->form_validation->run()===true)
            {
                $arr = array(
                    'USER_NAME'=>$this->input->post('username'),
                    'PASSWORD'=>sha1($this->input->post('password')),
                    'PHONE'=>$this->input->post('phone')
                );
                $this->user_model->set_user($arr);
                $result = $this->user_model->get_user_name($this->input->post('username'));
                if($result)
                {
                    $user_data = array(
                        'userid'=>$result['USER_ID'],
                        'username'=>$result['USER_NAME'],
                        'levers'=>$result['LEVERS'],
                        'image'=>$result['IMAGE'],
                        'phone'=>$result['PHONE'],
                        'login'=>true
                    );
                    $this->session->set_userdata($user_data);
                    redirect('info/');
                }
            }
        }

        $this->load->view('signup');
    }

    //验证规则回调函数
    public function username_check($str)
    {
        if($this->user_model->is_user($str))
        {
            $this->form_validation->set_message('username_check', '用户已存在');
            return false;
        }
        else
        {
            return true;
        }
    }

    public function user_check()
    {
        if($this->input->is_ajax_request())
        {
            $name = $this->input->post('username');
            if($this->user_model->is_user($name))
            {
                echo '0';//存在用户返回0，验证失败
            }
            else
            {
                echo '1';//不存在用户返回1，验证成功
            }
        }
    }

    //验证规则回调函数
    public function cap_check($str)
    {
        if(strcasecmp($str, $this->session->userdata('cap_word'))==0)
        {
            $this->session->unset_userdata('cap_word');
            return true;
        }
        else
        {
            $this->session->unset_userdata('cap_word');
            $this->form_validation->set_message('cap_check', '验证码错误');
            return false;
        }
    }

    public function captcha_check()
    {
        if($this->input->is_ajax_request())
        {
            $val = $this->input->post('captcha');
            $val1 = $this->session->userdata('cap_word');
            //$this->session->unset_userdata('cap_word');
            if(strcasecmp($val, $val1)==0)
            {
                echo '1';
            }
            else
            {
                echo '0';
            }
        }
    }

    public function get_captcha()
    {
        $cap = new ValidateCode();
        $this->session->set_userdata('cap_word', $cap->getCode());
        $cap->doimg();
    }

    public function signout()
    {
        $this->session->sess_destroy();
        $this->load->view('main');
    }

    public function signin()
    {
        if($this->input->post('username'))
        {
            $config = array(
                array(
                    'field'=>'username',
                    'label'=>'用户名',
                    'rules'=>'trim|min_length[3]|max_length[12]|xss_clean'
                ),
                array(
                    'field'=>'captcha',
                    'label'=>'验证码',
                    'rules'=>'callback_cap_check'
                )
            );
            $this->form_validation->set_rules($config);
            if($this->form_validation->run()===true)
            {
                $result = $this->user_model->get_user_name($this->input->post('username'));
                if($result)
                {
                    if(strcmp($result['PASSWORD'], sha1($this->input->post('password')))==0)
                    {
                        $user_data = array(
                            'userid'=>$result['USER_ID'],
                            'username'=>$result['USER_NAME'],
                            'levers'=>$result['LEVERS'],
                            'image'=>$result['IMAGE'],
                            'phone'=>$result['PHONE'],
                            'login'=>true
                        );
                        $this->user_model->update_time($result['USER_ID']);
                        $this->session->set_userdata($user_data);
                        redirect('info/');
                    }
                }
            }
        }
        $this->load->view('signin');
    }
}

class ValidateCode
{
    private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
    private $code;//验证码
    private $codelen = 4;
    private $width = 125;
    private $height = 30;
    private $img;
    private $font;
    private $fontsize = 17;
    private $fontcolor;

    public function __construct()
    {
        $this->font = './fonts/Elephant.ttf';
    }

    private function createCode()
    {
        $_len = strlen($this->charset) - 1;
        for($i=0; $i<$this->codelen; $i++)
        {
            $this->code .= $this->charset[mt_rand(0, $_len)];
        }
    }

    private function createBg()
    {
        $this->img = imagecreatetruecolor($this->width, $this->height);
        $color = imagecolorallocate($this->img,255,255,255);
        imagefilledrectangle($this->img,
                             0,
                             $this->height,
                             $this->width,
                             0,
                             $color);
    }

    private function createFont()
    {
        $_x = $this->width / $this->codelen;
        for($i=0; $i<$this->codelen; $i++)
        {
            $this->fontcolor = imagecolorallocate($this->img,
                                                  mt_rand(0, 156),
                                                  mt_rand(0, 156),
                                                  mt_rand(0, 156));
            imagettftext($this->img,
                         $this->fontsize,
                         mt_rand(-30, 30),
                         $_x*$i+mt_rand(1, 5),
                         $this->height/1.5,
                         $this->fontcolor,$this->font,$this->code[$i]);
        }
    }

    private function createLine()
    {
        for($i=0; $i<6; $i++)
        {
            $color = imagecolorallocate($this->img,
                                        mt_rand(0,156),
                                        mt_rand(0,156),
                                        mt_rand(0,156));
            imageline($this->img,
                      mt_rand(0,$this->width),
                      mt_rand(0,$this->height),
                      mt_rand(0,$this->width),
                      mt_rand(0,$this->height),$color);
        }
        for($i=0; $i<100; $i++)
        {
            $color = imagecolorallocate($this->img,
                                        mt_rand(200,255),
                                        mt_rand(200,255),
                                        mt_rand(200,255));
            imagestring($this->img,
                        mt_rand(1,5),
                        mt_rand(0,$this->width),
                        mt_rand(0,$this->height),'*',$color);
        }
    }

    private function outPut()
    {
        header('Content-type:image/png');
        imagepng($this->img);
        imagedestroy($this->img);
    }

    public function doimg()
    {
        $this->createBg();
        $this->createCode();
        $this->createLine();
        $this->createFont();
        $this->outPut();
    }

    public function getCode()
    {
        return $this->code;
    }
}
